<template>
  <div class="device-log">
    <div class="header">
      <div class="title">
        <i class="fas fa-server"></i> 设备日志管理系统
      </div>
      <div class="refresh-data">
        <el-form :inline="true" label-width="100px">
          <el-form-item label="设备ID/UUID">
            <el-input
              ref="deviceIdInput"
              v-model="deviceIdOrUid"
              placeholder="请输入设备ID/UUID"
              class="serach"
              clearable
              @keyup.enter.native="queryInfo"
            />
          </el-form-item>

          <el-form-item label="自动刷新">
            <el-select
              v-model="timeInterval"
              style="width: 200px"
              @change="handleTimeInterval"
            >
              <el-option
                v-for="item in timeOptions"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" size="14" class="add-btn" @click="refreshData">
              刷新数据
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="device-info-section">
      <div class="info-cards">
        <!-- 设备标识信息 -->
        <div class="info-card">
          <div class="card-header">
            <div
              class="card-icon"
              :class="{
                'device-icon': !!deviceInfo.productImage
              }">
              <img
                width="50"
                :src="deviceInfo.productImage || productImage"
              >
            </div>
            <h3>设备标识</h3>
          </div>
          <div class="device-property">
            <label>设备ID：</label>
            <span>{{ deviceInfo.deviceId }}</span>
          </div>
          <div class="device-property">
            <label>设备UUID：</label>
            <span>{{ deviceInfo.deviceUuid }}</span>
          </div>
          <div class="device-property">
            <label>设备名称：</label>
            <span>{{ deviceInfo.deviceName }}</span>
          </div>
          <div class="device-property">
            <label>产品ID：</label>
            <span>{{ deviceInfo.productId }}</span>
          </div>
          <div class="device-property">
            <label>产品名称：</label>
            <span>{{ deviceInfo.productName }}</span>
          </div>
          <div class="device-property">
            <label>设备类型：</label>
            <span>{{ deviceInfo.deviceType === '1' ? '子设备' : (deviceInfo.deviceType === '0' ? '网关设备' : '') }}</span>
          </div>
          <div class="device-property">
            <label>归属网关ID：</label>
            <span>{{ deviceInfo.gatewayId }}</span>
          </div>
          <div class="device-property">
            <label>归属网关：</label>
            <span>{{ deviceInfo.gatewayName }}{{ deviceInfo.gatewayProductId ? `(${deviceInfo.gatewayProductId})` : '' }}</span>
          </div>
        </div>

        <!-- 设备状态 -->
        <div class="info-card">
          <div class="card-header">
            <div class="card-icon">
              📶
            </div>
            <h3>设备状态</h3>
          </div>
          <div class="device-property">
            <label>在线状态：</label>
            <span class="status on">{{ deviceStatus.state === 'online' ? '在线' : (deviceStatus.state === 'offline' ? '离线' : '') }}</span>
          </div>
          <div class="device-property">
            <label>状态更新时间：</label>
            <span>{{ deviceStatus.updateStateTimestamp && formatTimestamp(deviceStatus.updateStateTimestamp) }}</span>
          </div>
          <div class="device-property">
            <label>信号强度：</label>
            <span>{{ deviceStatus.signal }}</span>
          </div>
          <div class="device-property">
            <label>ZIGBEE版本：</label>
            <span>{{ deviceStatus.otaInfoList && deviceStatus.otaInfoList.length && deviceStatus.otaInfoList[0].efirmwareName }}</span>
          </div>
          <div
            v-for="(item, i) in deviceStatus.otaInfoList"
            :key="i"
            class="device-property"
          >
            <label>{{ item.efirmwareName }}版本：</label>
            <span>
              {{ item.version }}
              <span v-if="item.version !== item.newVersion">
                （有新版本: {{ item.newVersion }}）
              </span>
            </span>
          </div>

        </div>

        <!-- 家庭信息 -->
        <div class="info-card">
          <div class="card-header">
            <div class="card-icon">
              🏠
            </div>
            <h3>归属信息</h3>
          </div>
          <!-- 所属家庭 -->
          <div class="device-property">
            <label>所属家庭：</label>
            <span>{{ (deviceSpace.spaceName || '') + (deviceSpace.spaceId ? '(' + deviceSpace.spaceId + ')' : '') }}</span>
          </div>

          <!-- 所属房间 -->
          <div class="device-property">
            <label>所属房间：</label>
            <span>{{ (deviceSpace.roomName || '') + (deviceSpace.roomId ? '(' + deviceSpace.roomId + ')' : '') }}</span>
          </div>

          <!-- 家庭所有者 -->
          <div class="device-property">
            <label>家庭所有者：</label>
            <span>{{ (deviceSpace.ownerPhone || '') + (deviceSpace.ownerId ? '(' + deviceSpace.ownerId + ')' : '') }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="note">
      <i class="fas fa-info-circle"></i>
      <div>
        <strong>说明：</strong>数据存储时间为14天，支持日志数据导出。
      </div>
    </div>

    <div class="tabs">
      <div v-for="tab in tabs" :key="tab.index" class="tab-pane" :class="{ 'tab-active': activeName === tab.index }" @click="handleTabs(tab.index)">
        <div class="tab-box">
          <span class="tab-title">{{ tab.title }}</span>
        </div>
      </div>
    </div>

    <div class="contain">
      <component
        :is="activeTabComponent"
        ref="activeComponentRef"
        :exist="exist"
        :device-id-or-uid="deviceId"
        :device-id="deviceId"
        :device-type="deviceInfo && deviceInfo.deviceType"
        :query-info="queryInfo"
      />
    </div>
  </div>
</template>
<script>
import { deviceContent } from '@/api/device/log2'
import logDetails from './components/logDetails.vue'
import localDeviceLogs from './components/localDeviceLogs.vue'
import constructionAppLog from './components/constructionAppLog.vue'
import constructionDeviceLog from './components/constructionDeviceLog.vue'
export default {
  name: 'deviceLog',
  components: { logDetails, localDeviceLogs, constructionAppLog, constructionDeviceLog },
  data() {
    return {
      activeName: 1, // 显示详情列表索引
      tabs: [
        { index: 1, num: '01', title: '日志详情', component: 'logDetails' },
        { index: 2, num: '02', title: '设备本地日志', component: 'localDeviceLogs' },
        { index: 3, num: '03', title: '施工APP日志', component: 'constructionAppLog' },
        { index: 4, num: '04', title: '施工设备日志', component: 'constructionDeviceLog' }
      ],
      timeInterval: 'none', // 自动刷新时间间隔
      timeOptions: [
        { key: '3', label: '3秒' },
        { key: '10', label: '10秒' },
        { key: '30', label: '30秒' },
        { key: 'none', label: '关闭' }
      ],
      deviceIdOrUid: '', // 设备ID或UUID
      deviceId: '', // 设备ID
      deviceIdInput: '', // 输入的设备ID
      deviceInfo: {}, // 设备标识信息
      deviceStatus: {}, // 设备状态信息
      deviceSpace: {}, // 设备归属信息
      autoRefreshInterval: null, // 自动刷新定时器
      productImage: 'https://smart.miligc.com:30900/upms/0MLSP0101A0R.png', // 产品默认图片
      exist: false, // 是否存在设备
      activeComponentRef: null // 当前激活组件的引用
    }
  },
  computed: {
    activeTabComponent() {
      const tab = this.tabs.find(tab => tab.index === this.activeName)
      return tab ? tab.component : null
    }
  },
  created() {
    this.$nextTick(() => {
      if (!this.deviceIdOrUid) {
        // 聚焦设备ID输入框
        if (this.$refs.deviceIdInput && typeof this.$refs.deviceIdInput.focus === 'function') {
          this.$refs.deviceIdInput.focus()
        }
        // 弹出提示
        this.$message({
          message: '请输入设备ID/UUID',
          type: 'warning',
          duration: 3000
        })
      } else {
        this.queryInfo()
      }
    })
  },
  methods: {
    /**
     * 查询设备列表
     * current 当前页码
     * size 每页条数
     */
    queryInfo() {
      const params = {
        deviceIdOrUid: this.deviceIdOrUid
      }
      deviceContent(params).then(res => {
        const data = res.data.data
        this.deviceInfo = data.deviceInfo || {}
        this.deviceStatus = data.deviceStateAndOta || {}
        this.deviceSpace = data.deviceSpace || {}
        this.deviceId = data.deviceInfo?.deviceId || ''
        this.exist = data.exist
        if (this.activeName === 1) {
          this.$nextTick(() => {
            this.$refs.activeComponentRef.loadList()
          })
        } else if (this.activeName === 2) {
          this.$nextTick(() => {
            this.$refs.activeComponentRef.localLogsList()
          })
        }
        // if (this.activeName === 1 && this.exist && this.deviceId) {
        //   this.$nextTick(() => {
        //     this.$refs.activeComponentRef.queryProperties()
        //   })
        // }
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },

    handleTabs(index) {
      this.activeName = index
      if (!this.deviceIdOrUid) {
        this.$message({
          message: '请输入设备ID/UUID',
          type: 'warning',
          duration: 3000
        })
      } else {
        this.queryInfo()
      }
    },
    refreshData() {
      if (!this.deviceIdOrUid) {
        this.$message({
          message: '请输入设备ID/UUID',
          type: 'warning',
          duration: 3000
        })
        return
      }
      this.queryInfo()
    },

    handleTimeInterval() {
      if (!this.deviceIdOrUid) {
        this.$message({
          message: '请输入设备ID/UUID',
          type: 'warning',
          duration: 3000
        })
        return
      }
      clearInterval(this.autoRefreshInterval)
      this.autoRefreshInterval = null
      if (this.timeInterval === 'none') return

      const interval = Number(this.timeInterval) * 1000
      if (isNaN(interval) || interval <= 0) return

      this.autoRefreshInterval = setInterval(() => {
        this.queryInfo()
      }, interval)
    },

    formatTimestamp(timestamp) {
      const date = new Date(Number(timestamp))
      const Y = date.getFullYear()
      const M = String(date.getMonth() + 1).padStart(2, '0')
      const D = String(date.getDate()).padStart(2, '0')
      const h = String(date.getHours()).padStart(2, '0')
      const m = String(date.getMinutes()).padStart(2, '0')
      const s = String(date.getSeconds()).padStart(2, '0')
      return `${Y}-${M}-${D} ${h}:${m}:${s}`
    }
  }
}
</script>
<style lang="scss" scoped>
.device-log {
  margin: 0 auto;
  background: white;
  border-radius: 12px;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.08);
  // overflow: hidden;
  padding: 25px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    padding-bottom: 20px;
    border-bottom: 1px solid #eaeef5;

    .title {
      font-weight: 700;
      font-size: 24px;
      color: #1a3353;
      display: flex;
      align-items: center;
      gap: 12px;

      i {
        color: #275fe8;
        font-size: 26px;
      }
    }

    .refresh-data {
      display: flex;
      align-items: center;
      gap: 15px;
    }
  }

  .device-info-section {
    margin-bottom: 30px;

    .info-cards {
      display: flex;
      gap: 25px;
      margin-bottom: 30px;
      flex-wrap: wrap;

      .info-card {
        flex: 1;
        min-width: 300px;
        font-size: 14px;
        color: #333;
        background-color: #f8fbff;
        border: 1px solid #e6edf5;
        border-radius: 12px;
        padding: 25px;
        position: relative;
        overflow: hidden;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);

        .card-header {
          display: flex;
          align-items: center;
          margin-bottom: 20px;
          padding-bottom: 15px;
          border-bottom: 1px solid #eaeef5;

          .card-icon {
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #e3f2fd, #bbdefb);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 15px;
            color: #1a73e8;
            font-size: 24px;

            h3 {
              font-size: 18px;
              color: #1a3353;
            }
          }

          .device-icon {
            background: none;

            img {
              width: 50px;
              height: 50px;
            }
          }
        }

        .device-property {
          display: flex;
          margin-bottom: 16px;
          line-height: 1.6;

          label {
            min-width: 100px;
            font-weight: 600;
            color: #5a6c87;
          }

          span {
            color: #1a3353;
            flex: 1;
          }

          // .status {
          //   font-weight: 600;
          //   padding: 2px 8px;
          //   border-radius: 4px;
          // }

          // .on {
          //   background-color: #e8f5e9;
          //   color: #2e7d32;
          // }
        }
      }

      .info-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
      }
    }
  }
}
  .note {
    background-color: #e3f2fd;
    border: 1px solid #275fe8;
    border-radius: 12px;
    padding: 18px;
    margin-bottom: 30px;
    color: #1a3353;
    font-size: 14px;
    line-height: 1.6;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    display: flex;
    gap: 12px;

    strong {
      color: #275fe8;
    }
  }

  .tabs {
    display: flex;
    margin-top: 27px;
    color: #808080;
    padding-bottom: 8px;
    border-bottom: 1px solid #DEDEDE;
    gap: 10px;

    .tab-pane {
      padding: 0 15px;
      text-align: center;
      position: relative;
      cursor: pointer;
      transition: color 0.3s;

      .tab-box {
        position: relative;
        padding: 0 10px;

        .tab-title {
          padding: 7px 0;
          cursor: pointer;
          display: block;
          font-weight: 500;
        }
      }
    }

    .tab-pane.tab-active .tab-title {
      color: #275FE8;
      border-bottom: 3px solid #275FE8;
      margin-bottom: -2px;
    }
  }

  .contain {
    margin-top: 25px;
    background: #fff;
    border-radius: 12px;
    padding: 25px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    min-height: 300px;
    border: 1px solid #eaeef5;
  }
</style>
